<template>
  <div class="vocabulary-accumulation-practice">
    <button @click="goToHome" class="home-button">返回首页</button>
    <div class="flashcard-container" v-if="currentCard">
      <div class="flashcard">
        <div class="word-header">
          <h2>{{ currentCard.word }}</h2>
          <p class="phonetic" v-if="currentCard.phonetic">[{{ currentCard.phonetic }}]</p>
        </div>
        
        <div class="card-content">
          <div class="main-info">
            <div class="info-item">
              <span class="label">词性</span>
              <span class="value">{{ currentCard.partOfSpeech || '暂无' }}</span>
            </div>
            
            <div class="definition-box">
              <span class="label">释义</span>
              <p class="definition-text" v-html="sanitizeHtml(currentCard.definition) || '暂无'"></p>
            </div>
          </div>
          
          <div class="secondary-info" v-if="currentCard.examples || currentCard.synonyms || currentCard.antonyms">
            <div class="info-row" v-if="currentCard.examples">
              <div class="info-item example-item">
                <span class="label">例句</span>
                <p class="example-text" v-html="sanitizeHtml(currentCard.examples)"></p>
              </div>
            </div>
            
            <div class="info-row">
              <div class="info-item synonym-item" v-if="currentCard.synonyms">
                <span class="label">近义词</span>
                <p class="synonym-text" v-html="sanitizeHtml(currentCard.synonyms)"></p>
              </div>
              
              <div class="info-item antonym-item" v-if="currentCard.antonyms">
                <span class="label">反义词</span>
                <p class="antonym-text" v-html="sanitizeHtml(currentCard.antonyms)"></p>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="flashcard-controls">
        <el-button type="primary" @click="previousCard" :disabled="currentIndex === 0">
          <el-icon><arrow-left /></el-icon> 上一张 (←)
        </el-button>
        <el-button type="primary" @click="nextCard" :disabled="currentIndex === totalCards - 1">
          下一张 (→) <el-icon><arrow-right /></el-icon>
        </el-button>
      </div>
      <div class="progress-info">
        <el-progress :percentage="((currentIndex + 1) / totalCards) * 100" :format="progressFormat" />
        <p>当前进度: {{ currentIndex + 1 }} / {{ totalCards }}</p>
      </div>
    </div>
    <div class="study-summary" v-else-if="cards.length > 0">
      <h2>学习完成</h2>
      <el-button type="primary" @click="restartStudy">重新学习</el-button>
    </div>
    <div class="no-vocabulary" v-else>
      <div class="no-vocabulary-content">
        <el-icon class="no-vocabulary-icon"><Document /></el-icon>
        <h2>暂无词汇数据</h2>
        <p>您还没有添加任何词汇，请先到词汇管理页面添加词汇</p>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { ElMessage } from 'element-plus';
import { ArrowLeft, ArrowRight, Refresh, Document } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import { getVocabularyList } from '@/api/vocabulary';
import { modifyQuestionContentImageSizeInHTML } from '@/utils/htmlUtils';
import type { VocabularyWord } from '@/types/vocabulary';

// 添加HTML清理函数
const sanitizeHtml = (html: any) => {
  if (!html) return '';
  // 简单的HTML清理，实际项目中建议使用专门的库
  const cleanedHtml = html.replace(/<script[^>]*>.*?<\/script>/gi, '')
             .replace(/<iframe[^>]*>.*?<\/iframe>/gi, '')
             .replace(/javascript:/gi, '');
  
  // 调用修改图片和视频大小的函数
  return modifyQuestionContentImageSizeInHTML(cleanedHtml);
};

interface FlashCard extends VocabularyWord {
  id: number;
  word: string;
  phonetic?: string;
  definition: string;
  examples: string;
  partOfSpeech: string;
  synonyms?: string;
  antonyms?: string;
}

const currentIndex = ref(0);
const totalCards = ref(0);
const currentCard = ref<FlashCard | null>(null);

const cards = ref<FlashCard[]>([]);

// 获取词汇数据
const fetchVocabularyData = async () => {
  try {
    // 检查是否有保存的练习参数
    const savedPracticeParams = sessionStorage.getItem('practiceParams');
    let requestParams = {
      pageNum: 1,
      pageSize: 1000, // 默认获取所有词汇用于练习
      keyword: '' // 空字符串表示不进行关键词筛选
    };
    
    if (savedPracticeParams) {
      try {
        const params = JSON.parse(savedPracticeParams);
        // 如果是词汇积累模块的练习参数，处理count参数
        if (params.module === 'vocabulary-accumulation' && params.params) {
          const practiceParams = params.params;
          if (practiceParams.count === 0) {
            // 选择全部，保持默认pageSize
            console.log('获取全部词汇');
          } else if (practiceParams.count > 0) {
            // 选择固定数量，设置pageSize为指定数量
            requestParams.pageSize = practiceParams.count;
            console.log(`获取${practiceParams.count}个词汇`);
          }
        }
      } catch (e) {
        console.error('解析练习参数失败:', e);
      }
    }
    
    // 传递正确的参数以匹配后端接口
    const response: any = await getVocabularyList(requestParams);
    if (response.code === 200) {
      // 从response.data.list中获取词汇列表
      const vocabularyList = response.data.list.map((item: any) => ({
        id: item.id,
        word: item.word,
        phonetic: item.phonetic || item.pronunciation || '',  // 修正发音字段映射
        definition: item.definition,
        examples: item.examples || '', // 修正例句字段映射，与接口定义一致
        partOfSpeech: item.partOfSpeech || '', // 词性
        synonyms: item.synonyms || '', // 近义词
        antonyms: item.antonyms || '' // 反义词
      }));
      cards.value = vocabularyList;
      totalCards.value = cards.value.length;
      loadNextCard();
    } else {
      ElMessage.error(response.message || '获取词汇数据失败');
    }
  } catch (error: any) {
    console.error('获取词汇数据失败:', error);
    ElMessage.error('获取词汇数据失败');
  }
};

const handleKeydown = (event: KeyboardEvent) => {
  if (event.key === 'ArrowLeft' || event.key === 'ArrowUp') {
    event.preventDefault();
    previousCard();
  } else if (event.key === 'ArrowRight' || event.key === 'ArrowDown') {
    event.preventDefault();
    nextCard();

  }
};

onMounted(() => {
  fetchVocabularyData();
  window.addEventListener('keydown', handleKeydown);
});

onBeforeUnmount(() => {
  window.removeEventListener('keydown', handleKeydown);
});

const loadNextCard = () => {
  if (currentIndex.value < cards.value.length && cards.value.length > 0) {
    currentCard.value = cards.value[currentIndex.value];
  } else {
    currentCard.value = null; // 显示学习总结或无词汇提示
  }
};



const previousCard = () => {
  if (currentIndex.value > 0) {
    currentIndex.value--;
    loadNextCard();
  }
};

const nextCard = () => {
  if (currentIndex.value < totalCards.value - 1) {
    currentIndex.value++;
    loadNextCard();
  }
};

const progressFormat = (percentage: number) => {
  return `${percentage.toFixed(0)}%`;
};

const restartStudy = () => {
  currentIndex.value = 0;
  loadNextCard();
};

const router = useRouter();

const goToHome = () => {
  router.push('/');
};
</script>

<style scoped>
.vocabulary-accumulation-practice {
  width: 100%;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4edf9 100%);
  padding: 40px 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

/* 确保通过v-html渲染的内容中的图片能正确显示 */
:deep(.definition-text) img,
:deep(.example-text) img,
:deep(.synonym-text) img,
:deep(.antonym-text) img {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  margin: 8px 0;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

:deep(.definition-text) p,
:deep(.example-text) p,
:deep(.synonym-text) p,
:deep(.antonym-text) p {
  margin: 8px 0;
  line-height: 1.6;
}

:deep(.definition-text) strong,
:deep(.example-text) strong,
:deep(.synonym-text) strong,
:deep(.antonym-text) strong {
  font-weight: 600;
}

:deep(.definition-text) em,
:deep(.example-text) em,
:deep(.synonym-text) em,
:deep(.antonym-text) em {
  font-style: italic;
}

.flashcard-container {
  max-width: 600px; /* 缩小卡片容器最大宽度 */
  width: 100%;
  text-align: center;
}

.flashcard {
  background: white;
  border-radius: 12px; /* 减小圆角 */
  padding: 0;
  margin-bottom: 20px; /* 减小底部边距 */
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1); /* 调整阴影 */
  cursor: default;
  position: relative;
  min-height: 300px; /* 减小最小高度 */
  backdrop-filter: blur(10px);
  overflow: hidden;
}

.flashcard:hover {
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.15);
}



@keyframes fadeIn {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}



.word-header {
  background: linear-gradient(135deg, #007aff 0%, #5ac8fa 100%);
  color: white;
  padding: 18px 24px; /* 减小内边距 */
  text-align: center;
  position: relative;
  overflow: hidden;
}

.word-header::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grid" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M 10 0 L 0 0 0 10" fill="none" stroke="rgba(255,255,255,0.1)" stroke-width="0.5"/></pattern></defs><rect width="100" height="100" fill="url(%23grid)"/></svg>');
  opacity: 0.3;
}

.word-header h2,
.word-header .phonetic {
  position: relative;
  z-index: 1;
}

.card-content {
  padding: 20px 24px; /* 减小内边距 */
  display: flex;
  flex-direction: column;
  gap: 16px; /* 减小间距 */
}

.main-info {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.secondary-info {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-row {
  display: flex;
  gap: 20px;
}

.info-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.label {
  font-weight: 600;
  color: #007aff;
  font-size: 14px; /* 减小字体大小 */
  letter-spacing: 0.5px;
}

.value {
  font-size: 18px;
  color: #2c3e50;
  font-weight: 500;
}

.definition-box {
  background-color: rgba(0, 122, 255, 0.05);
  border-left: 4px solid #007aff;
  padding: 16px;
  border-radius: 0 8px 8px 0;
}

.definition-text {
  font-size: 16px; /* 减小字体大小 */
  line-height: 1.6;
  color: #2c3e50;
  margin: 0;
  font-weight: 500;
}

.example-item {
  background-color: rgba(88, 86, 214, 0.05);
  border-radius: 8px;
  padding: 16px;
  border-left: 3px solid #5856d6;
}

.example-text {
  font-size: 14px; /* 减小字体大小 */
  line-height: 1.6;
  color: #34495e;
  margin: 0;
  font-style: italic;
  font-weight: 400;
}

.synonym-item {
  background-color: rgba(52, 199, 89, 0.05);
  border-radius: 8px;
  padding: 16px;
  border-left: 3px solid #34c759;
}

.synonym-text {
  font-size: 14px; /* 减小字体大小 */
  line-height: 1.5;
  color: #27ae60;
  margin: 0;
  font-weight: 500;
}

.antonym-item {
  background-color: rgba(255, 59, 48, 0.05);
  border-radius: 8px;
  padding: 16px;
  border-left: 3px solid #ff3b30;
}

.antonym-text {
  font-size: 14px; /* 减小字体大小 */
  line-height: 1.5;
  color: #e74c3c;
  margin: 0;
  font-weight: 500;
}

.flashcard h2,
.flashcard .phonetic {
  opacity: 0;
  animation: fadeIn 0.5s ease-out forwards;
}

.flashcard h2 {
  animation-delay: 0.1s;
  font-size: 28px; /* 减小字体大小 */
  margin-bottom: 6px; /* 减小底部边距 */
  color: #ffffff;
  font-weight: 700;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}

.flashcard .phonetic {
  animation-delay: 0.2s;
  color: rgba(255, 255, 255, 0.95);
  font-style: italic;
  margin-top: 0;
  font-weight: 500;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.25);
  font-size: 16px; /* 减小字体大小 */
}

.word-header {
  opacity: 0;
  animation: slideDown 0.6s ease-out forwards;
}

.card-content {
  opacity: 0;
  animation: fadeIn 0.8s ease-out 0.3s forwards;
}

.main-info {
  opacity: 0;
  animation: slideUp 0.6s ease-out 0.4s forwards;
}

.secondary-info {
  opacity: 0;
  animation: slideUp 0.6s ease-out 0.6s forwards;
}

@keyframes slideDown {
  from { opacity: 0; transform: translateY(-20px); }
  to { opacity: 1; transform: translateY(0); }
}

@keyframes slideUp {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}



/* 移除重复的.flashcard h2样式定义，使用上面的定义 */

.example {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #d2d2d7;
}

.flashcard-controls {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-bottom: 30px;
  animation: fadeIn 0.5s ease-out;
}

.flashcard-controls .el-button {
  transition: all 0.3s ease;
  min-width: 100px; /* 减小最小宽度 */
  border-radius: 10px; /* 减小圆角 */
  height: 36px; /* 减小高度 */
  font-size: 14px; /* 减小字体大小 */
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05); /* 调整阴影 */
}

.flashcard-controls .el-button:not(:disabled):hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.flashcard-controls .el-button--primary {
  background-color: #007aff;
  border-color: #007aff;
}

.flashcard-controls .el-button--primary.plain {
  background-color: transparent;
  border-color: #007aff;
  color: #007aff;
}

.progress-info {
  text-align: center;
  animation: fadeIn 0.5s ease-out;
  animation-delay: 0.2s;
  opacity: 0;
  animation-fill-mode: forwards;
}

.progress-info p {
  margin-top: 10px;
  color: #86868b;
  font-size: 14px;
}

.study-summary {
  background: white;
  border-radius: 12px;
  padding: 40px;
  text-align: center;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  max-width: 600px;
  width: 100%;
  animation: fadeIn 0.6s ease-out;
  position: relative;
  overflow: hidden;
  backdrop-filter: blur(10px);
}

.study-summary::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #007aff, #34c759);
}

.study-summary h2 {
  font-size: 32px;
  margin-bottom: 30px;
  color: #007aff;
  position: relative;
  display: inline-block;
  font-weight: 600;
}

.study-summary h2::after {
  content: '🎉';
  position: absolute;
  right: -40px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 24px;
  animation: bounce 1s ease infinite;
}

@keyframes bounce {
  0%, 100% { transform: translateY(-50%); }
  50% { transform: translateY(-70%); }
}

.study-summary .el-button {
  margin-top: 20px;
  padding: 12px 30px;
  font-size: 16px;
  transition: all 0.3s ease;
  border-radius: 12px;
  background-color: #007aff;
  border-color: #007aff;
  height: 44px;
}

.study-summary .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.summary-stats {
  display: flex;
  justify-content: space-around;
  margin-bottom: 40px;
}

.summary-stats .stat-item {
  text-align: center;
}

.summary-stats h3 {
  font-size: 18px;
  color: #86868b;
  margin-bottom: 10px;
  font-weight: 400;
}

.summary-stats p {
  font-size: 32px;
  font-weight: 600;
  color: #007aff;
}

.home-button {
  position: absolute;
  top: 20px;
  left: 20px;
  padding: 10px 16px;
  font-size: 15px;
  cursor: pointer;
  border: none;
  border-radius: 12px;
  background-color: rgba(0, 122, 255, 0.1);
  color: #007aff;
  transition: all 0.3s ease;
  font-weight: 500;
}

.home-button:hover {
  background-color: rgba(0, 122, 255, 0.15);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 无词汇时的样式 */
.no-vocabulary {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4edf9 100%);
}

.no-vocabulary-content {
  text-align: center;
  padding: 50px 40px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  max-width: 500px;
  width: 100%;
  animation: fadeIn 0.6s ease-out;
  backdrop-filter: blur(10px);
}

.no-vocabulary-icon {
  font-size: 64px;
  color: #c7c7cc;
  margin-bottom: 20px;
}

.no-vocabulary-content h2 {
  font-size: 24px;
  color: #1d1d1f;
  margin-bottom: 15px;
  font-weight: 600;
}

.no-vocabulary-content p {
  font-size: 16px;
  color: #86868b;
  margin-bottom: 30px;
  line-height: 1.6;
}

.no-vocabulary-content .el-button {
  padding: 12px 30px;
  font-size: 16px;
  transition: all 0.3s ease;
  border-radius: 12px;
  background-color: #007aff;
  border-color: #007aff;
  color: white;
  height: 44px;
}

.no-vocabulary-content .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 确保通过v-html渲染的内容中的图片能正确显示 */
:deep(.definition-text) img,
:deep(.example-text) img,
:deep(.synonym-text) img,
:deep(.antonym-text) img {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  margin: 8px 0;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

:deep(.definition-text) p,
:deep(.example-text) p,
:deep(.synonym-text) p,
:deep(.antonym-text) p {
  margin: 8px 0;
  line-height: 1.6;
  font-style: normal; /* 确保段落文本不使用斜体 */
}

:deep(.definition-text) strong,
:deep(.example-text) strong,
:deep(.synonym-text) strong,
:deep(.antonym-text) strong {
  font-weight: 600;
}

:deep(.definition-text) em,
:deep(.example-text) em,
:deep(.synonym-text) em,
:deep(.antonym-text) em {
  font-style: normal; /* 将斜体文本设置为正常字体 */
  font-weight: 500; /* 可以适当加粗以保持强调效果 */
}
</style>